package com.polaris.live.ui.live.activity.end.live

import android.os.Bundle
import android.os.CountDownTimer
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.StringUtils
import com.bumptech.glide.Glide
import com.gyf.immersionbar.ImmersionBar
import com.polaris.live.adapter.SpectatorEndAdapter
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbActivity
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.constant.LiveConst
import com.polaris.live.constant.UserConst
import com.polaris.live.databinding.ActivitySpectatorEndBinding
import com.polaris.live.im.sfs.bean.live.SendLiveCloseMessage
import com.polaris.live.interface_bag.PAGViewListener
import com.polaris.live.resp.back_resp.DisplayUserBean
import com.polaris.live.translation.R.string
import com.polaris.live.utils.CommonUtils
import com.polaris.live.utils.LiveUtils
import com.polaris.live.utils.OtherUserCacheUtils
import com.polaris.live.utils.getIntOrString
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.route.RoutePath
import com.polaris.live.utils.route.Router
import com.polaris.live.viewmodel.SpectatorEndViewModel
import com.polaris.live.widget.avatar.FrameImageUtils
import com.polaris.live.widget.pag.AddFollowView.Companion.LIVE_ADD_FOLLOWE
import jp.wasabeef.glide.transformations.BlurTransformation
import kotlinx.coroutines.launch
import org.libpag.PAGView

/**
 * SpectatorEndActivity
 *
 * @author Created by 半仙 on 2023/10/9/009 11:16
 */
class SpectatorEndActivity : BaseVbActivity<SpectatorEndViewModel, ActivitySpectatorEndBinding>() {

    //三秒定时器，到时间自动切换到下一个
    private val mTime: TimeCount by lazy {
        TimeCount(NEXTLIVE, 1000)
    }

    private val mAdapter by lazy { SpectatorEndAdapter() }

    private var mSendLiveData: SendLiveCloseMessage? = null

    private val mFromType by lazy {
        intent.getIntOrString("fromType", 1)
    }

    private var mLivesLive: DisplayUserBean? = null

    override fun initImmersionBar() {
        ImmersionBar.with(this)
            .transparentStatusBar()
            .titleBar(mBinding.icBack)
            .fullScreen(false)
            .transparentNavigationBar()
            .init()
    }

    override fun initView(savedInstanceState: Bundle?) {

        mSendLiveData = intent.getParcelableExtra("data")

        initListener()
        initObsever()

        mSendLiveData?.anchorId?.let {
            mViewModel.getBasisInfoUser(it)

            when (mFromType) {
                LiveConst.Type.LIVE_AND_MATCH -> {
                    mViewModel.getLivesRecommend()
                    mViewModel.getLivesLive(1, it)//这里只要不是0就行  所以干脆写死1
                }

                LiveConst.Type.PARTY_LIVE -> {
                    mViewModel.getPartyRecommend()
                    mViewModel.getLoadMore()
                    mBinding.tvEndTitle.text = StringUtils.getString(string.room_end)
                }

                LiveConst.Type.VIDEO_PARTY -> {
                    mViewModel.getPartyRecommend()
                    mViewModel.getLoadMore()
                    mBinding.tvEndTitle.text = StringUtils.getString(string.room_end)
                }

                LiveConst.Type.PARTY_GAME_LIVE -> {
                    mViewModel.getGamePartyRecommend()
                    mViewModel.getGameParty()
                    mBinding.tvEndTitle.text = StringUtils.getString(string.room_end)
                }
            }
        }
        mBinding.recycler.apply {
            adapter = mAdapter
            layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
        }

        mBinding.otherAddFollow.apply {
            setPathType(LIVE_ADD_FOLLOWE)
            addListener(object : PAGViewListener {
                override fun onAnimationEnd(p0: PAGView?) {
                    super.onAnimationEnd(p0)
                    mBinding.otherAddFollow.visibility = View.GONE
                    mBinding.ivOtherAdd.visibility = View.GONE
                }
            })
            setRepeatCount(1)
        }
    }

    private fun initListener() {
        mBinding.icBack.setOnSingleClickListener {
            finish()
        }
        mBinding.userAvatar.setOnSingleClickListener {
            mSendLiveData?.anchorId?.let { it1 ->
                Router.instance.setPath(RoutePath.USER_SPACE_ACTIVITY)
                    .withInt("page", UserConst.From.LIVE)
                    .withLong("userId", it1).navigation()
            }
        }
        mBinding.otherAddFollow.setOnSingleClickListener {
            mSendLiveData?.anchorId?.let { it1 -> mViewModel.addFollower(it1) }
        }

        mBinding.nextLive.setOnSingleClickListener {
            goNextLive()
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            val item = mAdapter.data[position]
            when (item.base.liveType) {
                LiveConst.Type.PARTY_GAME_LIVE -> {
                    Router.instance.setPath(RoutePath.PARTY_GAME_SPECTATOR_ACTIVITY)
                        .withLong(LiveConst.Params.ANCHORID, item.base.userId)
                        .navigation(this@SpectatorEndActivity)
                }

                LiveConst.Type.PARTY_LIVE, LiveConst.Type.VIDEO_PARTY -> {
                    Router.instance.setPath(RoutePath.PARTY_SPECTATOR_ACTIVITY)
                        .withLong(LiveConst.Params.ANCHORID, item.base.userId)
                        .withInt(LiveConst.Params.LIVETYPE, item.base.liveType)
                        .navigation(this@SpectatorEndActivity)
                }

                else -> {
                    LiveUtils.toSpectator(item).navigation(this@SpectatorEndActivity)
                }
            }
            finish()
        }
    }

    private fun initObsever() {
        mViewModel.userBasisLiveData.observe(this) { resultState ->
            parseState(resultState, {
                OtherUserCacheUtils.addUser(it)
                if (it.relation?.followed == true) {
                    mBinding.otherAddFollow.visibility = View.GONE
                    mBinding.ivOtherAdd.visibility = View.GONE
                } else {
                    mBinding.otherAddFollow.visibility = View.VISIBLE
                    mBinding.ivOtherAdd.visibility = View.VISIBLE
                }
                mBinding.avFv.setFrameImage(FrameImageUtils.urlToFrameImageBean(it.decoration?.avatarFrame))
                mBinding.userAvatar.setImageUrlMiddle(it.avatar)
                Glide.with(this).load(ImageUtils.imgPath(it.avatar))
                    .transform(BlurTransformation(15, 3))
                    .into(mBinding.backBigImg)

                mBinding.nickName.text = it.nickname
                mBinding.cvCountry.setCountry(it.profile.country)
                val richs = it.account.richs
                val charms = it.account.charms

                if (it.sex.let { CommonUtils.isMan(it) }) {
                    mBinding.otherLevel.setRichsLevel(richs)
                } else {
                    mBinding.otherLevel.setCharmsLevel(charms)
                }
                mBinding.vipView.setVipLevel(it.profile.vipLevel)
            }, {
                when (it.errCode) {
                    CommonConst.ErrorCode.USER_LOGGED_OUT, //用户已注销
                    CommonConst.ErrorCode.ACCOUNT_SHUT_DOWN,
                        -> {//该账号已经被关小黑屋
                        mSendLiveData?.anchorId?.let { id ->
                            OtherUserCacheUtils.removeUser(id)
                        }
                    }
                }
            })
        }
        mViewModel.followerLiveData.observe(this) { resultState ->
            parseState(resultState, {
                ToastGravity.showGravity(string.follower_succeed)
                mBinding.otherAddFollow.play()
                mBinding.ivOtherAdd.visibility = View.GONE
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }
        mViewModel.livesRecommendLiveData.observe(this) { resultState ->
            parseState(resultState, {
                mAdapter.setList(it)
            })
        }
        mViewModel.partyRecommendLiveData.observe(this) { resultState ->
            parseState(resultState, {
                mAdapter.setList(it)
            })
        }
        mViewModel.liveLiveData.observe(this) { resultState ->
            parseState(resultState, {
                if (it.code == 200) {
                    if (it.result == null) {
                        mBinding.nextLive.text = StringUtils.getString(string.close)
                    } else {
                        mLivesLive = it.result
                        mTime.start()
                    }
                } else {
                    ToastGravity.showGravity(it.errorMessage)
                }
            })
        }
        mViewModel.liveLoadMoreLiveData.observe(this) { resultState ->
            parseState(resultState, {
                if (it.code == 200) {
                    if (it.result == null) {
                        mBinding.nextLive.text = StringUtils.getString(string.close)
                    } else {
                        mLivesLive = it.result
                        mTime.start()
                    }
                } else {
                    ToastGravity.showGravity(it.errorMessage)
                }
            })
        }
        mViewModel.partyGameRecommendLiveData.observe(this) { resultState ->
            parseState(resultState, {
                mAdapter.setList(it)
            })
        }
        mViewModel.gamePartyData.observe(this) { resultState ->
            parseState(resultState, {
                if (it.code == 200) {
                    if (it.result == null) {
                        mBinding.nextLive.text = StringUtils.getString(string.close)
                    } else {
                        mLivesLive = it.result
                        mTime.start()
                    }
                } else {
                    ToastGravity.showGravity(it.errorMessage)
                }
            })
        }
    }

    internal inner class TimeCount(millisInFuture: Long, countDownInterval: Long) :
        CountDownTimer(millisInFuture, countDownInterval) {

        override fun onTick(millisUntilFinished: Long) {
            mBinding.nextLive.text =
                "${StringUtils.getString(string.next_live)}(${millisUntilFinished / 1000})"
        }

        override fun onFinish() {
            goNextLive()
        }

    }

    private fun goNextLive() {
        val liveId = mLivesLive?.base?.userId
        if (liveId != null) {
            lifecycleScope.launch {
                try {
                    when (mLivesLive?.base?.liveType) {
                        LiveConst.Type.PARTY_GAME_LIVE -> {
                            Router.instance.setPath(RoutePath.PARTY_GAME_SPECTATOR_ACTIVITY)
                                .withLong(LiveConst.Params.ANCHORID, liveId).navigation(this@SpectatorEndActivity)
                        }

                        LiveConst.Type.PARTY_LIVE -> {
                            Router.instance.setPath(RoutePath.PARTY_SPECTATOR_ACTIVITY)
                                .withInt(LiveConst.Params.LIVETYPE, LiveConst.Type.PARTY_LIVE)
                                .withLong(LiveConst.Params.ANCHORID, liveId).navigation(this@SpectatorEndActivity)
                        }

                        LiveConst.Type.VIDEO_PARTY -> {
                            Router.instance.setPath(RoutePath.PARTY_SPECTATOR_ACTIVITY)
                                .withInt(LiveConst.Params.LIVETYPE, LiveConst.Type.VIDEO_PARTY)
                                .withLong(LiveConst.Params.ANCHORID, liveId).navigation(this@SpectatorEndActivity)
                        }

                        else -> {
                            LiveUtils.toSpectator(liveId).navigation(this@SpectatorEndActivity)
                        }
                    }
                    finish()
                } catch (t: Throwable) {
                    ToastGravity.showGravity(t.message)
                }
            }
        } else {
            finish()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mTime.cancel()
    }

    companion object {

        const val NEXTLIVE = 5000L
    }
}